package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;

import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.User;
import com.itheima.ydd.dto.cateDto;
import com.itheima.ydd.dto.indexDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;

import com.itheima.ydd.service.impl.YddTagServiceImpl;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/index")
@CrossOrigin
@Slf4j
public class IndexController {
   @Autowired
   private ISysUserService sysUserService;

   @Autowired
   private ISysConfigService sysConfigService;

   //--------------------后端主页注入service------------------------------
   @Autowired
   private IYddAdvposService iYddAdvposService;
   @Autowired
   private ISysUserService iSysUserService;
   @Autowired
   private IYddCateService iYddCateService;
   @Autowired
   private IYddArticleService iYddArticleService;
   @Autowired
   private YddTagServiceImpl yddTagService;
   @Autowired
   private IYddAdvimgService iYddAdvimgService;
   @Autowired
   private IYddUserService iYddUserService;

   @GetMapping("/baseInfo")
   public ResultData homePage() {
      //1 创建后端主页对象
      indexDto indexDto = new indexDto();//baseInfo
      //1 各类cate 文章 article 的发布数量
      //1.1查询
      // 1.2 创建文章分类对象集合

      ArrayList<cateDto> cateDtos = new ArrayList<>();// 后端主页属性柱状图对象
      List<YddCate> catedtolist = iYddCateService.list();
      for (YddCate yddCate : catedtolist) {
         //为catedto赋值
         cateDto cateDto = new cateDto();
         cateDto.setId(yddCate.getId());
         cateDto.setCatename(yddCate.getCatename());

         //1.3 根据yddcate的id 去 article(文章)表中找cateid = ?
         LambdaQueryWrapper<YddArticle> ll = new LambdaQueryWrapper<>();
         ll.eq(YddArticle::getCateid, yddCate.getId());//双标联查
         int artcatecount = iYddArticleService.count(ll);//各类文章的数量
         cateDto.setNum(artcatecount);
         log.info("///////////////////2222222555555//{}",cateDto);
         //将文章分类对象放入集合
         cateDtos.add(cateDto);
      }
      //将 有点大主页信息统计 对象 属性 进行赋值
      indexDto.setAllCates(cateDtos);
      //2 广告位总数
      int count = iYddAdvposService.count();
      log.info("/////////////1111111111111111////////////////{}", count);
      indexDto.setAdvposNum(count);
      //标签总数
      indexDto.setTagNum(yddTagService.count());
      //管理员总数
      int count1 = iSysUserService.count();
      log.info("/////////////1111111111111111/////////////////{}", count1);
      indexDto.setAdminNum(count1);
      //文章总数
      indexDto.setArticleNum(iYddArticleService.count());
      //平台文章分类总数
      indexDto.setCateNum(iYddCateService.count());
      //广告图总数
      indexDto.setAdvImgNum(iYddAdvimgService.count());
      //后端主页对象的,最新注册新用户数据属性 赋值
      //利用mybatis 中 注入 sql语句,查询最后新注册用户的 七个数据
      //利用注解  SQL语句 select *  from ydd_user order by id desc  limit 7
      List<YddUser> yddusers = iYddUserService.getLast7();
      indexDto.setNewUser(yddusers);
      //热门文章数据
      //利用mybatis 中 注入 sql语句,查询article表中的 最后七个数据,并依据点击数来排序
      //利用注解  SQL语句 select *  from article order by click desc  limit 7
      List<YddArticle> hotarticles =  iYddArticleService.gethotarticle7();
      indexDto.setHotArticle(hotarticles);
      //用户性别分析,设置indexdto的usersex对象值
      //select count(sex) from ydd_user where group by(sex)
      //获得全部的用户数量
      int newusercount = iYddUserService.count();
      //获得用户对象
      User user = indexDto.getUser();
      //为对象赋值所有的用户数量
      user.setTotle(newusercount);
      //查询用户中,所有性别为女生的数量
      LambdaQueryWrapper<YddUser> ll = new LambdaQueryWrapper<>();
      //条件查询性别为男的用户
      ll.eq(YddUser::getSex,0);//
      int man_num = iYddUserService.count(ll);
      user.setUserMan(man_num);
      //条件查询性别为女的用户数量
      LambdaQueryWrapper<YddUser> ll2 = new LambdaQueryWrapper<>();
      ll2.eq(YddUser::getSex,1);
      int woman_num = iYddUserService.count(ll2);
      user.setUserWoman(woman_num);
      indexDto.setUser(user);
      log.info("/////////////////33333//////////////////////{}",indexDto.toString());
      //将模型数据喂给前端
      ResultData resultData = new ResultData();
      resultData.setErrno(0);
      resultData.setErrmsg("");
      resultData.setData(indexDto);
      return resultData;
   }

   //---------------用户登录方法-------------------------
   @PostMapping("/login")
   public R login(@RequestBody SysUser sysUser) {
      log.info("登陆用户：{}", sysUser.toString());

      String loginName = sysUser.getLoginName();
      LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(SysUser::getLoginName, loginName);
      SysUser one = sysUserService.getOne(wrapper);

      if (one == null) {
         return R.error("账号不存在");
      } else if (one.getStatus() == 0) {
         return R.error("账号已禁用");
      }

      String password = sysUser.getPassword();
      if (one.getPassword().equals(generatePassword(password))) {
         //把用户id 加密进token里

         // 生成token信息
         Map retMap = new HashMap();
         Map tokenMap = new HashMap<>();
         String roleId = one.getRoleId()
                 .replace("[", "")
                 .replace("]", "")
                 .replace("\"", "");

         tokenMap.put("userId", one.getId());
         tokenMap.put("roleId", roleId);

         String token = JwtUtils.getToken(tokenMap);
         retMap.put("token", token);
         return R.success("token", JwtUtils.getToken(tokenMap));
      }
      return R.error("密码错误");

   }


   @GetMapping("/getConfig")
   public R systemConfig() {
      LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(SysConfig::getTabValue, "system");
      List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

      HashMap<String, String> map = new HashMap<>();
      for (SysConfig sysConfig : sysConfigs) {
         map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
      }

      return new R(map, "", 0);

   }

   @PostMapping("/profile")
   public R profile(HttpServletRequest request) {
      String token = request.getHeader("x-token");

      Claims claims = JwtUtils.getClaims(token);
      Long userId = Long.valueOf((String) claims.get("userId"));

      log.info("用户id:{}", userId);
      return sysUserService.profile(userId);
   }

   /**
    * md5加密
    *
    * @param password 密码
    */
   private String generatePassword(String password) {
      return DigestUtils.md5DigestAsHex(password.getBytes());
   }

}